package fun.wlfj.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fun.wlfj.factory.CashSystemFactory;
import fun.wlfj.vo.PayList;
import fun.wlfj.vo.Product;
import fun.wlfj.vo.User;

/**
 * Servlet implementation class AddProductServlet
 */
@WebServlet("/AddProductServlet")
public class AddProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddProductServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Do not request me directly ! QAQ");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int PayListID = Integer.parseInt(request.getParameter("PayListID"));
		String ProductShortName = request.getParameter("ProductShortName");
		int Count = Integer.parseInt(request.getParameter("Count"));
		User user = (User) request.getSession().getAttribute("User");
		String msg = null;
		if (user != null && ProductShortName != null) {
			List<Product> list = CashSystemFactory.getProductDao().findByShortName(ProductShortName);
			if(list.size() >= 1) {
				Product product = list.get(0);
				if (product != null) {
					product.setCount(Count);
					msg = CashSystemFactory.getPayListDao(user)
							.addProduct(new PayList(user.getUserID(), PayListID, null), product);
				}
			}
		}else {
			response.sendRedirect("clearEnv");
			return;
		}
		if(msg != null)
			msg = "来自数据库触发器的消息:" + msg;
		request.getSession().setAttribute("message", msg);
		response.sendRedirect("makePay.jsp");
	}

}
